import time
import tkinter
import threading
import os
# import pyperclip
from tkinter import messagebox
from tkinter import ttk

import serial

status = 0


def open_com():
    global status
    global com
    if status == 0:
        try:
            status = 1
            what_com = choose_com_combobox.get()
            bot = int(bot_combobox.get())
            com = serial.Serial(what_com, bot, timeout=1)
            # com.open()
            status_show.config(text=f'{what_com}已打开，接收数据中', bg='lightgreen')
            # success_bytes = com.write(b'REEL2103221842566PART150649140000QTY5000GRN500497265500012021MPNACR164-473FVDateCode1055LotBatch3N2 C10205E107 107160ExpDate2022-03-18\r\n')
            # # b表示bytes类型, 直接发送字符串报错
            # print(success_bytes)  # 发送数据长度
            while status == 1:
                # data = com.readline()
                # data = com.readall()  # .readall()有时候会接收不全
                # data = com.read(5)
                count_com = com.inWaiting()     # .inWaiting返回串口接收的数据个数
                if count_com > 0:               # 如果串口有数据
                    time.sleep(0.1)             # 等个0.1秒等数据接收完，防止数据接收不全
                    count_com = com.inWaiting()     # .inWaiting重新返回串口接收的数据个数
                    data = com.read(count_com)      # .read(count_com)将新返回的串口接收数据个数全部读出来
                    # print(data, type(data))
                    # start_time = time.time()
                    # end_time = time.time()
                    # xx = []
                    # if end_time - start_time < over_time:
                    # if start_time + over_time < time.time():
                    # print('data', data)
                    old_text.delete(0.0, 'end')
                    old_text.insert(0.0, str(data))
                    try:
                        new_text.delete(0.0, 'end')
                        # old_detail = old_text.get(0.0, 'end')
                        # print(old_detail)
                        encode1 = encode_combobox.get()
                        new_detail = data.decode(encode1)
                        new_detail = new_detail.replace('', '@')
                        new_detail = new_detail.replace('', '@')
                        new_detail = new_detail.replace('', '@')
                        new_text.insert('end', new_detail)
                        # print(new_detail)
                    except:
                        new_text.insert('end', '转换编码格式失败，选择正确的编码格式再试下')
                        # messagebox.showerror(title='报错', message='转换编码格式失败，选择正确的编码格式再试下')
                time.sleep(0.1)
        except:
            messagebox.showerror(title='报错', message='打开com失败')
            status_show.config(text='打开com失败', bg='pink')
    else:
        messagebox.showerror(title='报错', message='打开串口失败,串口不存在或已开启')
        status_show.config(text='打开串口失败,串口不存在或已开启', bg='pink')


def thread_open_com():
    thread_add = threading.Thread(target=open_com)
    thread_add.start()


def close_com():
    try:
        global status
        status = 0
        com.close()
        status_show.config(text='com口已关闭', bg='yellow')
    except:
        messagebox.showerror(title='报错', message='关闭串口失败,未定义打开的串口')


def clear_old_text():
    old_text.delete(0.0, 'end')


def clear_new_text():
    new_text.delete(0.0, 'end')


# def change_format():
#     # try:
#     new_text.delete(0.0, 'end')
#     old_detail = old_text.get(0.0, 'end')
#     print(old_detail)
#     encode1 = encode_combobox.get()
#     new_detail = old_detail.decode(f'{encode1}')
#     new_text.insert('end', new_detail)
#     # except:
#     #     messagebox.showerror(title='报错', message='转换编码格式失败，选择正确的编码格式再试下')


# def copy_newtext():
#     text = new_text.get(0.0, 'end')
#     pyperclip.copy(text[2:])


win = tkinter.Tk()
win.title('串口调试工具            Author : Shi Sixian   ')
win.geometry('600x520')
win.option_add("*Font", "宋体 12")
# win.attributes('-topmost', 1)
# win.config(bg='lightgreen')


# old_label = tkinter.Label(win, text='COM口收到的内容:')
# old_label.place(x=20, y=5)
# old_text = tkinter.Text(win, width=91, height=4, font='Times 9')
# old_text.place(x=20, y=25)

# new_label = tkinter.Label(win, text='转换后需要的内容:')
# new_label.place(x=20, y=115)
# new_text = tkinter.Text(win, width=91, height=4, font='Times 9')
# new_text.place(x=20, y=135)
#
# copy_button = tkinter.Button(win, text='复制需要的内容', height=2, width=68, bg='skyblue', command=copy_newtext)
# copy_button.place(x=20, y=210)

choose_com_label = tkinter.Label(win, text='设置com口和波特率:')
choose_com_label.place(x=20, y=20)
choose_com_combobox = ttk.Combobox(win, width=5)
choose_com_combobox.place(x=180, y=20)
choose_com_combobox['values'] = ('COM1', 'COM2', 'COM3', 'COM4', 'COM5', 'COM6', 'COM7', 'COM8', 'COM9', 'COM10',
                                 'COM11', 'COM12', 'COM13', 'COM14', 'COM15', 'COM16', 'COM17', 'COM18')
choose_com_combobox.set('COM3')
bot_combobox = ttk.Combobox(win, width=6)
bot_combobox.place(x=250, y=20)
bot_combobox['values'] = (110, 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 38400, 56000, 57600, 115200)
bot_combobox.set(9600)
# bot = bot_combobox.get()
# print('bot', type(bot), bot)

old_label = tkinter.Label(win, text='COM口收到的内容:')
old_label.place(x=20, y=120)
clear_old_button = tkinter.Button(win, text='清空接收内容', bg='skyblue', font='宋体 8', command=clear_old_text)
clear_old_button.place(x=490, y=120)
old_text = tkinter.Text(win, width=91, height=7, font='Times 9')
old_text.place(x=20, y=140)

start_button = tkinter.Button(win, text='打开串口', command=thread_open_com)
start_button.place(x=370, y=17)

close_button = tkinter.Button(win, text='关闭串口', command=close_com)
close_button.place(x=490, y=17)

status_show = tkinter.Label(win, text='暂时没有打开的串口', bg='yellow', width=68)
status_show.place(x=20, y=70)

remark_label1 = tkinter.Label(win, text='默认接收格式是以bytes接收，因内置的自动优化机制，大部分通用字符可以直\n接显示（数字和字母），'
                                        '也可以选择对应的编码格式将接收到的内容转换出来。\n'
                                        '如果有中文，请选择utf-8编码格式。                                     \n'
                                        '如果是VDA标签，请选择ASCII编码格式,程序就会自动将不可见分隔符转换为@  ')
remark_label1.place(x=20, y=260)
remark_label2 = tkinter.Label(win, text='选择编码格式:')
remark_label2.place(x=20, y=350)
encode_combobox = ttk.Combobox(win, width=10)
encode_combobox.place(x=150, y=350)
encode_combobox['values'] = ('ASCII', 'GBK', 'GB18030', 'GB2312', 'UTF-8', 'ANSI', 'UTF-16', 'ISO8859-1')
encode_combobox.set('GBK')
# change_format_button = tkinter.Button(win, text='转换到下方输入框', command=change_format)
# change_format_button.place(x=270, y=347)
clear_new_button = tkinter.Button(win, text='清空转换内容', bg='skyblue', font='宋体 8', command=clear_new_text)
clear_new_button.place(x=490, y=360)
new_text = tkinter.Text(win, width=91, height=7, font='Times 9')
new_text.place(x=20, y=380)


# if __name__ == '__main__':
#     thread_com_format()


def about_show():
    win2 = tkinter.Toplevel(win)
    win.attributes('-disabled', 1)
    win2.title('about')
    win2.geometry('600x590')
    # win2.option_add("*Font", "华文行楷 12")

    about_text = tkinter.Text(win2, width=59, height=29, font=("楷体", 15))  # , "italic"))
    about_text.place(x=2, y=2)
    about_details = '关于\n\n\n之前用的一款小鸭子串口调试工具，功能还可以，就是广告有点多，界面有点花，红黄蓝搭配的，整得像不正经博彩网站是的，' \
                    '于是即兴花了4小时写了这款纯净版的。\n\n\n此工具主要用于调试串口扫描枪，检验扫描枪的串口是否正常，如果扫描枪能通过' \
                    'com口扫进这个工具里，但扫不进MES软件里，说明扫描枪是能用的，这时候可以检查下MES的com口设置和扫描枪的com口是否对应。' \
                    '\n\n如果扫描枪不能通过con口扫到这个工具里，就试下能否往txt里扫，\n' \
                    '如果能直接往txt里扫，说明扫描枪是直连模式，不是串口模式，需要将枪调成串口模式。\n' \
                    '如果不能往txt里扫，也不能往这个工具里扫，就拔掉扫码枪，重新插上。看下多了那个com口，再试下。\n\n\n' \
                    '如果扫码枪按不亮，那就是扫码枪硬件坏了\n\n\n' \
                    '因为此工具主要是查看com口扫描枪的，所以只写了读取功能，没有写入功能，如果想扩展写入串口功能，或者套接字等，可联系作者。' \
                    '\n施小四\nQQ：565056149'
    about_text.insert(0.0, about_details)
    about_text.config(state='disabled')

    def do_cancel():
        win.attributes('-disabled', 0)
        win2.destroy()

    win2.resizable(False, False)
    win2.protocol("WM_DELETE_WINDOW", do_cancel)
    win2.mainloop()


about_button = tkinter.Button(win, text='?', bg='skyblue', command=about_show)
about_button.place(x=575, y=490)


def quit1():
    os._exit(0)


win.resizable(False, False)
win.protocol("WM_DELETE_WINDOW", quit1)
win.mainloop()
